package com.etc.controller;

import com.etc.entity.Shoppingcart;
import com.etc.entity.User;
import com.etc.service.ShoppingcartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.Id;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/ShoppingcartController")
public class ShoppingcartController {
    @Autowired
    ShoppingcartService service;

    @RequestMapping("/add")
    public void add(Shoppingcart record){
        Long userId =record.getUserId();
        Long goodsId = record.getGoodsId();
        Integer goodsCount = record.getGoodsCount();

        List<Shoppingcart> list = service.dofindByUserIdAndGoodsId(userId, goodsId);
        if(list.size() == 0){
             service.add(record);
        }else {
            Integer count = list.get(0).getGoodsCount();
            count = count + goodsCount;
            record.setGoodsCount(count);
            service.updateCount(record,userId,goodsId);
        }
    }

    @RequestMapping("/find")
    public List<Shoppingcart> find(@RequestParam("userId")Long userId){
        List<Shoppingcart> list = service.doFindByUserId(userId);
/*        User frontUser = (User) request.getSession().getAttribute("frontUser");
        System.out.println(frontUser);*/
        return list;
    }

    @RequestMapping("/update")
    public void update(@RequestParam("userId")Long userId,
                       @RequestParam("goodsId")Long goodsId,
                       @RequestParam("goodsCount")int goodsCount
                       ){
            service.doupdatGoodsCount(goodsCount,userId,goodsId);
    }

    @RequestMapping("/delS")
    public void delS(@RequestParam("userId")Long userId,
                       @RequestParam("goodsId")Long goodsId
    ){
        service.doDelS(userId, goodsId);
    }

    @RequestMapping("/delA")
    public void delA(@RequestParam("userId")Long userId
    ){
        service.doDelA(userId);
    }

    @RequestMapping("/success")
    public void success(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User frontUser = (User) request.getSession().getAttribute("frontUser");
        System.out.println(frontUser);

        Long id = frontUser.getId();
        System.out.println(id);
        request.getRequestDispatcher("/OrderSkuController/add?id="+id+"").forward(request, response);
    }
}
